package org.acooly.secretbox.ui;

import org.acooly.android.utils.StringUtils;
import org.acooly.android.utils.ToastUtils;
import org.acooly.secretbox.R;
import org.acooly.secretbox.common.BaseActivity;
import org.acooly.secretbox.service.UserService;
import org.acooly.secretbox.service.domain.User;
import org.acooly.secretbox.service.impl.UserServiceImpl;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

/**
 * 忘记密码
 * 
 * @author zhangpu
 * 
 */
public class ForgetPasswordActivity extends BaseActivity {

	private UserService userService;

	User user;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.forget_password);
		userService = new UserServiceImpl(this);
		user = userService.get();
		setTextView(R.id.forget_question, user.getQuestion());

		Button validateButton = (Button) getView(R.id.forget_validate);
		validateButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				validateAnswer();
			}
		});

		Button setNewButton = (Button) getView(R.id.forget_setnew);
		setNewButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				try {
					String password = getEditText(R.id.forget_pswd);
					String confirmPassword = getEditText(R.id.forget_confirmPswd);
					if (StringUtils.isBlank(password)) {
						throw new RuntimeException("登录密码不能为空");
					}
					if (StringUtils.isBlank(confirmPassword)) {
						throw new RuntimeException("确认密码不能为空");
					}

					if (!password.equals(confirmPassword)) {
						throw new RuntimeException("两次输入的密码不相同");
					}
					user.setPassword(password);
					userService.update(user);
					ForgetPasswordActivity.this.finish();
					Intent intent = new Intent(ForgetPasswordActivity.this, LoginActivity.class);
					startActivity(intent);
				} catch (Exception e) {
					ToastUtils.showShort(getApplicationContext(), e.getMessage());
				}

			}
		});

	}

	private void validateAnswer() {
		String answer = getTextView(R.id.forget_answer);
		if (StringUtils.equals(answer, user.getAnswer())) {
			getView(R.id.forget_anth_layout).setVisibility(View.GONE);
			getView(R.id.forget_setnew_layout).setVisibility(View.VISIBLE);
		} else {
			ToastUtils.showShort(this, "验证答案错误，请重试.");
		}
	}

}
